package net.jzysoft.app.ui;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatDelegate;

import com.lzy.okhttputils.OkHttpUtils;

import net.jzysoft.app.utils.DataManager;
import net.jzysoft.app.utils.SettingsUtil;

/**
 * Created by Administrator on 2016/7/13.
 */
public class App extends Application {

    /**
     * 全局上下文，方便使用
     */
    public static Context context;
    public static Handler mHandler;
    public static LocalBroadcastManager localBroadcastManager;


    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();
        context =this;
        if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(SettingsUtil.KEY_NIGHT_MODE, false)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
        //必须调用初始化
        OkHttpUtils.init(this);
        //以下都不是必须的，根据需要自行选择
        //final PushAgent mPushAgent = PushAgent.getInstance(this);
        localBroadcastManager= LocalBroadcastManager.getInstance(context);//注册广播
        // 首先重新设置包名
      /*  mPushAgent.setResourcePackageName(R.class.getPackage().getName());
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            *//**
             * 自定义消息的回调方法
             *//*
            public void  handleMessage(Context var1, UMessage var2) {
                Log.d("XXXX", "handleMessage: " + var2.toString());

                super.handleMessage(var1, var2);
                //接受到推送消息 发送广播 newfragemntmessage页面接收消息
                Intent intent = new Intent("com.jz_badgview");
                localBroadcastManager.sendBroadcast(intent);
            }
            *//**
             * 自定义消息的回调方法
             *//*
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                new Handler(getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // 对于自定义消息，PushSDK默认只统计送达。若开发者需要统计点击和忽略，则需手动调用统计方法。
                        boolean isClickOrDismissed = true;
                        if(isClickOrDismissed) {
                            //自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        } else {
                            //自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }

            *//**
             * 自定义通知栏样式的回调方法
             *//*
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }

        };
        mPushAgent.setMessageHandler(messageHandler);
        mPushAgent.setDebugMode(true);
        *//**
         * 自定义行为的回调处理
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * *//*
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                if (msg.extra.get("groupLXID") != null || !TextUtils.isEmpty(msg.extra.get("groupLXID"))) {
                    CommUtility.openActivity(context, msg.extra.get("activity"),msg.extra.get("fkid"),msg.extra.get("groupLXID"));
                }else {
                    CommUtility.openActivity(context, msg.extra.get("activity"),msg.extra.get("fkid"),"-1");
                }

            //   Toast.makeText(context, msg.extra.get("activity"), Toast.LENGTH_LONG).show();
            }
        };
        //使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        //参考http://bbs.umeng.com/thread-11112-1-1.html
        //CustomNotification Handler notificationClickHandler = new CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                String s = deviceToken;
                DataManager.deviceToken = deviceToken;
                Log.d("devicetoken", s);
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });
        new Thread() {
            @Override
            public void run() {
                mPushAgent.register(new IUmengRegisterCallback() {
                    @Override
                    public void onSuccess(String deviceToken) {
                        //注册成功会返回device token
                        String s = deviceToken;
                        DataManager.deviceToken = deviceToken;
                        Log.d("devicetoken", s);
                    }

                    @Override
                    public void onFailure(String s, String s1) {
                    }
                });
            }
        }.run();
        DataManager.mPushAgent = mPushAgent;*/
        //以下都不是必须的，根据需要自行选择
        OkHttpUtils.getInstance()//
                .debug("OkHttpUtils")                                              //是否打开调试
                .setConnectTimeout(OkHttpUtils.DEFAULT_MILLISECONDS)               //全局的连接超时时间
                .setReadTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS)                  //全局的读取超时时间
                .setWriteTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS);                 //全局的写入超时时间
        //.setCookieStore(new MemoryCookieStore())                           //cookie使用内存缓存（app退出后，cookie消失）
        //.setCookieStore(new PersistentCookieStore())                       //cookie持久化存储，如果cookie不过期，则一直有效
               /* .addCommonHeaders(headers)                                         //设置全局公共头
                .addCommonParams(params);                                          //设置全局公共参数*/
        DataManager.context = getApplicationContext();
       /* //图片加载器配置
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() //
                .showImageForEmptyUri(R.drawable.banner) //
                .showImageOnFail(R.drawable.banner) //
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .bitmapConfig(Bitmap.Config.RGB_565) //default is ARGB_8888, it will use as double memory as RGB_565
                .cacheInMemory(true) //
                .cacheOnDisk(true) //
                .build();//
        ImageLoaderConfiguration config = new ImageLoaderConfiguration//
                .Builder(getApplicationContext())//
                .defaultDisplayImageOptions(defaultOptions)//
                .discCacheSize(50 * 1024 * 1024)//
                .discCacheFileCount(1000)// 缓存一百张图片
                .writeDebugLogs()//
                .build();//
        ImageLoader.getInstance().init(config);
        DataManager.DEFAULT_SAVE_IMAGE_PATH = CommUtility.getDiskCacheDir(context) + File.separator + "yezhubaotemp" + File.separator + "oss_img" + File.separator;
        FileUtils.createOrExistsDir(DataManager.DEFAULT_SAVE_IMAGE_PATH);*/

      /*  //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。html5

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);*/
    }
}
